<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use fast\Random;
use think\Db;

/**
 *
 *
 * @icon fa fa-file
 */
class Wxlogin extends Api
{

    /**
     * Unit模型对象
     */
    private $appid = 'wx2bab6cd1400f48bb';
    private $secret = '2c4eec8b958e7be9c627ac1f369663de';

    protected $model = null;
    protected $noNeedRight = ["dologin", "hello"];
    protected $noNeedLogin = ["dologin", "hello"];

    public function _initialize()
    {
        parent::_initialize();

        return true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 微信绑定
     */
    public function index()
    {
        $user_id = $this->request->param('user_id', 0);
        if (!$user_id) {
            $this->error('参数错误');
        }

        $user = $this->model->find($user_id);
        if (!$user) {
            $this->error('用户不存在');
        }

        $this->view->assign('user', $user);
        return $this->view->fetch();
    }

    /**
     * 生成绑定二维码
     */
    public function qrcode()
    {
        $user_id = $this->request->param('user_id', 0);
        if (!$user_id) {
            $this->error('参数错误');
        }

        // 生成唯一绑定码
        $bind_code = md5(uniqid() . $user_id . time());

        // 存储绑定码到缓存，设置有效期为5分钟
        cache('wxbind_' . $bind_code, $user_id, 300);

        // 生成微信扫码URL，这里需要替换为您的微信公众号或小程序的实际URL
        $url = "/ysapi/v1/wechat/bind?code={$bind_code}";

        $this->success('', ['bind_code' => $bind_code, 'url' => $url]);
    }

    /**
     * 检查绑定状态
     */
    public function check()
    {
        $bind_code = $this->request->param('bind_code', '');
        if (!$bind_code) {
            $this->error('参数错误');
        }

        // 从缓存中获取绑定状态
        $bind_status = cache('wxbind_status_' . $bind_code);

        if ($bind_status) {
            // 绑定成功，清除缓存
            cache('wxbind_' . $bind_code, null);
            cache('wxbind_status_' . $bind_code, null);
            $this->success('绑定成功');
        } else {
            $this->error('等待绑定');
        }
    }

    /**
     * - 需要在微信公众平台配置相应的权限
     *- 小程序需要在 app.json 中声明需要使用的接口
     *- 获取手机号需要企业主体小程序
     *- access_token 建议缓存使用，避免频繁请求
     *- 用户信息需要用户授权才能获取
     * 获取access_token
     */
    public function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
        $result = json_decode(file_get_contents($url), true);
        return $result['access_token'];
    }

    /**
     * 后端解密代码
     */
    public function decryptData()
    {
        $code = $this->request->post('code');
        //获取小程序的 token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response, true);
        if (isset($result['errcode'])) {
            return json([
                'code' => 1,
                'msg' => '获取 access_token 失败: ' . $result['errmsg']
            ]);
        }
        $access_token = $result['access_token'];
        // 通过 code 换取手机号
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
        $data = ['code' => $code];

        $response = curl_post($url, json_encode($data));
        $result = json_decode($response, true);

        if (isset($result['phone_info'])) {
            return json([
                'code' => 0,
                'msg' => '获取成功',
                'data' => $result['phone_info']
            ]);
        }

        // 第158行 - 获取失败
        return json(['code' => 500, 'msg' => '获取失败']);
    }


    /*
    获取用户信息
    */
    public function getUserInfo($openid)
    {
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $result = json_decode(file_get_contents($url), true);
        return $result;
    }

    /**
     * 微信绑定
     */
    public function bind()
    {
        $code = $this->request->param('code', '');

        if (!$code) {
            $this->error('参数错误');
        }

        // 获取session_key和openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);

        if (isset($result['errcode']) && $result['errcode'] != 0) {
            // 处理错误
            return json([
                'code' => $result['errcode'],
                'msg' => $result['errmsg']
            ]);
        }

        // 解析返回的 JSON 数据
        $result = json_decode($response, true);

        if (isset($result['errcode']) && $result['errcode'] != 0) {
            return json([
                'code' => $result['errcode'],
                'msg' => $result['errmsg']
            ]);
        }

        if ($result == null) {
            return json([
                'code' => 0,
                'msg' => '连接失败'
            ]);
        }
        //$result["openid"]=333;
        $openid = $result['openid'];
        $session_key = $result['session_key'];
        $unionid = "";
        if (isset($result['unionid'])) {
            $unionid = $result['unionid'];
        } else {
            $unionid = "";
        }


        // 更新用户信息
        $update = [
            'openid' => $result['openid'],
            'nickname' => isset($_REQUEST['nickname']) ? $_REQUEST['nickname'] : '',
            'username' => isset($_REQUEST['nickname']) ? $_REQUEST['nickname'] : '',
            'avatar' => (isset($_REQUEST['avatar']) && $_REQUEST['avatar'] != "") ? $_REQUEST['avatar'] : '/assets/img/avatar.png',
            'gender' => isset($_REQUEST['gender']) ? $_REQUEST['gender'] : 1,
        ];
        if (isset($result['unionid'])) {
            $update['unionid'] = $result['unionid'];
        }
        $user = Db::name('user')->where('openid', $result['openid'])->find();
        if ($user) {
            Db::name('user')->where('openid', $result['openid'])->update($update);
        } else {
            $update['group_id'] = 1;
            Db::name('user')->insert($update);
        }
        $user = Db::name('user')->where('openid', $result['openid'])->find();
        $this->success('绑定成功', ["userinfo" => $this->UserFilter($user)]);
    }

    /**
     * 解除绑定
     */
    public function unbind()
    {
        $user_id = $this->request->param('user_id', 0);
        if (!$user_id) {
            $this->error('参数错误');
        }

        $user = Db::name('user')->where('id', $user_id)->find();
        if (!$user) {
            $this->error('用户不存在');
        }

        // 清除微信绑定信息
        $user["openid"] = '';
        $user["unionid"] = '';
        $user["nickname"] = '';
        Db::name('user')->where('id', $user_id)->update();

        $this->success('解除绑定成功');
    }
    /**
     * 添加
     */
    /**
     * 添加 微信快捷登录
     */
    public function dologin()
    {
        // 获取小程序端传来的 code
        $code = $this->request->post('code');
        $mcode = $this->request->post('mcode');
        if (!$code) {
            return json([
                'code' => 1,
                'msg' => '缺少 code 参数'
            ]);
        }
        $session_key="";
        $unionid="";
        $openidarray = $this->get_wx_openid($code);
        if (empty($openidarray) || isset($openidarray["code"])) {
            //$this->error("获取openid失败,提示：".$openidarray["code"]);
        }
        if (isset($openidarray["openid"])) {
            $openid = $openidarray["openid"];
        }
        if(isset($openidarray["unionid"])){
            $unionid=$openidarray["unionid"];
        }
        if(isset($openidarray["session_key"])){
            $session_key=$openidarray["session_key"];
        }

        $salt = Random::alnum(6);
        // 可以将 openid 和 session_key 存储到数据库或缓存中
        // 这里以存储到数据库为例
        $openid=(isset($openid)&&$openid!="")?$openid:"";
        $user = Db::name('user')->where('openid', $openid)->find();
        if (!$user||isset($user)&&$user["mobile"]=="") {
            $this->error('请先同意绑定手机号！',[],"300");
        }
        //获取手机号码
        $mobile="";
        if ($mcode) {
            $mobile = $this->get_wx_mobile($mcode);
            if (is_array($mobile)||isset($mobile["code"])) {
                $this->error("获取手机号码失败,提示：".$mobile["msg"]);
            }
        }
        if (!$user&&$openid!="") {
            $data = [
                'nickname' => $mobile,
                'avatar' => '/assets/img/avatar.png',
                'mobile' => $mobile,
                'username' => $mobile,
                'password' => md5(md5("159456") . $salt),
                'level' => 0,
                'status' => 'normal',
                'salt' => $salt,
                'createtime' => time(),
                'group_id' => $_REQUEST["group_id"] > 0 ? $_REQUEST["group_id"] : 1,
                'openid' => $openid,
                'session_key' => $session_key,
                'unionid' => $unionid,
                'updatetime' => time(),
            ];
            $user_id = model("app\admin\model\User")->insertGetId($data);
            $user = Db::name('user')->find($user_id);
            $authorization = \app\admin\model\User::setApiToken($user);
            $this->success('注册成功', ['id' => $user['id'], 'isRegularUser' => true, 'userinfo' => $this->UserFilter($user), 'authorization' => $authorization]);
        }elseif($openid==""){
            $this->error('获取openid出错了！');
        } else {
            // 如果用户存在，则更新 session_key
            Db::name('user')->where('openid', $openid)->update([
                'session_key' => $session_key,
                'updatetime' => time()
            ]);
            $_REQUEST["group_id"] = empty($_REQUEST["group_id"]) ? 1 : $_REQUEST["group_id"];
            $user = Db::name('user')->where('openid', $openid)->where("group_id", $_REQUEST["group_id"])->find();
            $authorization = \app\admin\model\User::setApiToken($user);
            $this->success('登录成功', ['id' => $user['id'], 'userinfo' => $this->UserFilter($user), 'openid' => $openid, 'authorization' => $authorization]);
        }
     }


    // 微信游客登录
    public function loginByWechat()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('code不能为空');
        }

        // 1. 通过微信code换取openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code";


        $result = json_decode(file_get_contents($url), true);
        if (!isset($result['openid'])) {
            $this->error('微信登录失败：' . $result['errmsg']);
        }
        $openid = $result['openid'];

        // 2. 查询或创建游客账号
        $user = Db::name('user')->where(['openid' => $openid])->find();
        if (!$user) {
            // 创建游客账号
            $token = md5(uniqid() . time()); // 生成临时token
            $expireTime = time() + 86400; // 24小时有效期

            $userId = Db::name('user')->insertGetId([
                'openid' => $openid,
                'token' => $token,
                'user_type' => 2, // 标记为游客
                'expire_time' => $expireTime,
                'createtime' => time(),
            ]);
            $user = ['id' => $userId, 'token' => $token, 'expire_time' => $expireTime];
        }

        // 3. 返回登录凭证
        $this->success('登录成功', [
            'token' => $user['token'],
            'expire_time' => $user['expire_time'],
            'user_type' => $user['user_type'],
        ]);
    }

    public function UserFilter($user)
    {
        $newuser = [];
        $newuser['id'] = $user['id'];
        $newuser['openid'] = $user['openid'];
        $newuser['unionid'] = $user['unionid'];
        $newuser['group_id'] = $user['group_id'];
        $newuser['username'] = $user['username'];
        $newuser['nickname'] = $user['nickname'];
        $newuser['email'] = $user['email'];
        $newuser['mobile'] = $user['mobile'];
        $newuser['avatar'] = $user['avatar'];
        $newuser['gender'] = $user['gender'];
        $newuser['birthday'] = $user['birthday'];
        $newuser['latitude'] = $user['latitude'];
        $newuser['longitude'] = $user['longitude'];
        $newuser['address'] = $user['address'];
        $newuser['money'] = $user['money'];
        $newuser['city_id'] = $user['city_id'];
        return $newuser;
    }
}
